<template>
	<div class="imgUpload">
		<div :id="btnId" class="choiceBtn">选择文件</div>
	    <div class="word_list">
			<div class="list_item" v-for="(item,index) in word_list">
				<span>{{item.filename}} - {{item.size}}</span><span style="margin-left: 10px;">
				{{item.pro}} %</span>
				<span class="del" @tap="delitem('word',word_list,index)">
					<i class="iconfont icon-shanchu"></i>
				</span>
			</div>
		</div>
		<div class="video_list">
			<div class="list_item" v-for="(item,index) in video_list">
				<span>{{item.filename}} - {{item.size}}</span> <span style="margin-left: 10px;">
				{{item.pro}} %</span>
				<span class="del" @tap="delitem('mp4',video_list,index)">
					<i class="iconfont icon-shanchu"></i>
				</span>
			</div>
		</div>
		<div class="img_list" style="overflow: hidden;margin-top: 10px;">
			<div class="img_item" v-for="(item,index) in img_list" style="float: left;width: 80px;height: 135px;margin-right: 10px;">
				 <img :src="item.src" alt="" style="display: block;width: 80px;height:80px;">
				 <div style="font-size: 12px;text-align: center;width: 100%;overflow: hidden;height: 18px;white-space: nowrap;text-overflow: ellipsis;">{{item.filename}}</div> 
				 <div style="font-size: 12px; text-align: center;">{{item.pro}} %</div>
				 <div class="del" @tap="delitem('img',img_list,index)" style="text-align: center;">
					<i class="iconfont icon-shanchu icon-warning" style="font-size: 22px;"></i>
				 </div>
			</div>
		</div>
	</div>
</template>

<script>
	import plupload from "plupload";
	import baseUrl from "@/util/path.js";
	import TOKEN from "@/util/token.js"
	var accessid = "";
	var accesskey = "";
	var host = "";
	var policyBase64 = "";
	var signature = "";
	var callbackbody = "";
	var filename = "";
	var key = "";
	var expire = 0;
	var g_object_name = "";
	var g_object_name_type = "";
	var now = Date.parse(new Date()) / 1000;
	var timestamp = Date.parse(new Date()) / 1000;
	
	function send_request(ext)
	{
	    var postExt = ext.split('.')[1] ? ext.split('.')[1] : "";
	    var xmlhttp = null;
	    if (window.XMLHttpRequest)
	    {
	        xmlhttp=new XMLHttpRequest();
	    }
	    else if (window.ActiveXObject)
	    {
	        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	    }
	    if (xmlhttp!=null) {
	        // serverUrl是 用户获取 '签名和Policy' 等信息的应用服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
	        var serverUrl = baseUrl.wy + 'user/ststoken?id=10029&ext=' + postExt
	        xmlhttp.open( "get", serverUrl, false);
			xmlhttp.setRequestHeader("Authorization", 'Bearer '+ TOKEN);
	        xmlhttp.send( null );
	        return xmlhttp.responseText
	    }
	    else
	    {
	        alert("Your browser does not support XMLHTTP.");
	    }
	}
	
	 function previewImage(file, callback) {//file为plupload事件监听函数参数中的file对象,callback为预览图片准备完成的回调函数
	         var moxie = plupload.moxie;
	     if (!file || !/image\//.test(file.type)) return; //确保文件是图片
	     if (file.type == 'image/gif') {//gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
	         var fr = new moxie.image.Image();
	         fr.onload = function () {
	             callback(fr.result);
	             fr.destroy();
	             fr = null;
	         }
	         fr.readAsDataURL(file.getSource());
	     } else {
	         var preloader = new moxie.image.Image();
	         preloader.onload = function () {
	             //preloader.downsize(550, 400);//先压缩一下要预览的图片,宽300，高300
	             var imgsrc = preloader.type == 'image/jpeg' ? preloader.getAsDataURL('image/jpeg', 80) : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
	             callback && callback(imgsrc); //callback传入的参数为预览图片的url
	             preloader.destroy();
	             preloader = null;
	         };
	         preloader.load(file.getSource());
	     }
	 }
	
	export default {
	  props: {
	    btnId: ""
	  },
	  data() {
	    return {
	      url: this.msg || "",
		  word_list:[],
		  video_list:[],
		  img_list:[],
		  goid:'',
		  goId:[]
	    };
	  },
	  created() {
		  // console.log(this.$route.query.id);
		  this.goId = this.$route.query.id;
	  },
	  mounted() {
		 
		if(this.btnId == "upWord") {
			this.initPlUploaderWord();
		} 
		if(this.btnId == 'upImg') {
			this.initPlUploaderImg();
		}
		if(this.btnId == "upVideo") {
			this.initPlUploaderVideo();
		}
	  },
	  methods: {
	     async send_request(ext){
	     	var postExt = ext.split('.')[1] ? ext.split('.')[1] : "";
			const res = await this.$http({
				  url:'user/ststoken',
				  method:'post',
				  data:{
					  id:this.goId,
					  ext:postExt
				  }
			})
			
			if(res) {
				return res.data;
			} else {
				uni.showToast({
					icon: 'none',
					title: "没有获取到授权"
				})
			}
	     },
		async get_signature(ext)
		 {
		        // 可以判断当前expire是否超过了当前时间， 如果超过了当前时间， 就重新取一下，3s 作为缓冲。
			now = timestamp = Date.parse(new Date()) / 1000;
			if (expire < now + 3)
			{
				
				var postExt = ext.split('.')[1] ? ext.split('.')[1] : "";
				const res = await this.$http({
					  url:'user/ststoken',
					  method:'post',
					  data:{
						  id:this.goId,
						  ext:postExt
					  }
				})
                // const res = await this.send_request(ext);
			    // console.log('res',res);
				if(!res) {
					return;
				}
				 // console.log(res);
				// console.log(body);
				var obj = res;
				// console.log('obj',res);
				host = obj['host']
				policyBase64 = obj['policy']
				accessid = obj['accessKeyId']
				signature = obj['signature']
				expire = parseInt(obj['expire'])
				key = obj['key']
				// debugger;
				return true;
			}
			return false;
		},
		async set_upload_param(up, filename, ret,id,list) {
			var arrayTemp = filename.split('.');
			var length = arrayTemp.length;
			var postExt;
			if(length > 1) {
				postExt = arrayTemp[length - 1];
			} else {
				postExt = "";
			}
			console.log(postExt);
			if (ret == false)
			        {
						const res = await this.$http({
							  url:'user/ststoken',
							  method:'post',
							  data:{
								  id:this.goId,
								  ext:postExt
							  }
						})
						if(!res) {
							ret = false;
						} else {
							var obj = res;
							host = obj['host']
							policyBase64 = obj['policy']
							accessid = obj['accessKeyId']
							signature = obj['signature']
							expire = parseInt(obj['expire'])
							key = obj['key']
							ret = true;
						}
			        }
			        g_object_name =  key;
			        // $("#" + id).find('input').attr("data-key",g_object_name)
					if(list) {
						 // console.log(list);
						// var postExt = filename.split('.')[1];
						 list.forEach((item) =>{
							  item.ext = postExt;
							  if(item.id == id) {
								  item.file_key = g_object_name;
							  }
						 })
					}
			        var new_multipart_params = {
			            'key': g_object_name,
			            'policy': policyBase64,
			            'OSSAccessKeyId': accessid,
			            'success_action_status': '200', //让服务端返回200,不然，默认会返回204
			            'signature': signature,
			        };
			         // console.log('new_multipart_params',new_multipart_params);
			        // console.log(new_multipart_params);
			        up.setOption({
			            'multipart_params': new_multipart_params
			        });
			        up.start();
		},
		delitem(who,list,index) {
			list.splice(index,1);
			this.emit(who);
		},
		emit(who){
			if(who == 'mp4') {
				// console.log('emitMp4',this.video_list);	
				this.video_list = this.video_list.map((item) => {
					return {
						etag:item.etag,
						ext:"mp4",
						file_key:item.file_key,
                        filename:item.filename,  
                        id:item.id,
						pro:item.pro,
						size:item.size
					}
				})
				this.$emit("getList",{
					type:'mp4',
					list:this.video_list
				})
			}
			if(who == 'word') {
				this.$emit("getList",{
					type:'word',
					list:this.word_list
				})
			}
			if(who == 'img') {
				// console.log(this.img_list);	
				// this.img_list = this.img_list.map((item) => {
				// 	var ext = item.file_key;
				// 	console.log(ext);
				// 	// return {
				// 	// 	etag:item.etag,
				// 	// 	ext:ext,
				// 	// 	filename:item.filename,
				// 	// 	pro:item.pro,
				// 	// 	size:item.size,
				// 	// 	src:"",
				// 	// }
				// })
			 //    console.log('this.img_list',this.img_list);	
				this.$emit("getList",{
					type:'img',
					list:this.img_list
				})
			}
			// console.log('emit',obj);
		},
		initList() {
			this.video_list = [];
			this.word_list = [];
			this.img_list = [];
		},
		initPlUploaderVideo() {
			 const _this = this;
		     var uploader = new plupload.Uploader({
		     runtimes: "html5,flash,silverlight,html4",
		     browse_button: this.btnId,
		     multi_selection: false,
		    // container: document.getElementById('container'),
		    // flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
		    // silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
		     url: baseUrl.OccAli,
		    filters: {
		      mime_types: [
		          {title : "video files", extensions : "mp4,MP4,mov,MOV"},
		     ],
		      max_file_size: "1024mb" //最大只能上传10mb的文件
		      // prevent_duplicates: true //不允许选取重复文件
		    },
			
		    init: {
		      PostInit: function() {
		        // document.getElementById("ossfile").innerHTML = "";
		        // document.getElementById("postfiles").onclick = function() {
		        //   set_upload_param(uploader, "", false);
		        //   return false;
		        // };
				;
		      },
		      FilesAdded: function(up, files) {
				  //  = 
		        plupload.each(files, function(file) {
					if(_this.video_list.length < 1) {
						_this.video_list.push({
							id:file.id,
							filename:file.name,
							size:file.size,
							pro:0
						})
						_this.emit('mp4');
						_this.set_upload_param(uploader, file.name, false,file.id,_this.video_list);
					}
		        });
				//console.log(_this.word_list);
		      },
			
		      BeforeUpload: function(up, file) {
				// _this.set_upload_param(up, file.name, true);
		      },
			
		      UploadProgress: function(up, file) {
		        _this.video_list.forEach((item) => {
					if(item.id == file.id) {
						item.pro = file.percent;
						if (file.percent == 100 ) {
							item.pro = 99
						}
					}
				})
		      },
			
		      FileUploaded: function(up, file, info) {
		        if (info.status == 200) {
					// console.log(info);
					var array = info.responseHeaders.split("\r\n");
					var infoObj = {}
					array.forEach((item) => {
						  var arr = item.split(':');
						  if(arr.length > 1) {
							  infoObj[arr[0]] = arr[1].replace(/"/g,"").replace(/ /g, '');
						  }
					})
					// console.log(infoObj);
					// console.log(_this.video_list);
					_this.video_list.forEach((item) => {
						if (item.id == file.id) {
							item.etag = infoObj.etag;
							item.pro = 100;
						}
					})
					//console.log('上传视频完成video_list',_this.video_list);
					_this.emit('mp4')
		        } else if (info.status == 203) {
					console.log("上传到OSS成功，但是oss访问用户设置的上传回调服务器失败，失败原因是:" + info.response)
		        } else {
		          console.log(info.response)
		        }
		      },
			
		      Error: function(up, err) {
		        if (err.code == -600) {
					alert("选择的文件太大了,最大不能超过1G");	
		        } else if (err.code == -601) {
					alert("选择的文件后缀不对,支持m4格式上传");	
		        } else if (err.code == -602) {
					alert("这个文件已经上传过一遍了");
		        } else {
					console.log("Error xml:" + err.response) 
		        }
		      }
		    }
		  });
		  uploader.init();
		},
	    initPlUploaderWord() {
			const _this = this;
	        var uploader = new plupload.Uploader({
	        runtimes: "html5,flash,silverlight,html4",
	        browse_button: this.btnId,
	        url: baseUrl.OccAli,
			max_file_size: "100mb",
			max_retries: 3,   //允许重试次数
			chunk_size: '10mb', //分块大小
			rename: true, //重命名
			unique_names: true, //文件名称唯一性
			multi_selection: false,//true:ctrl多文件上传, false 单文件上传 
	       filters: {
	          mime_types: [
	       		  {title : "doc files", extensions : "docx,ppt,pptx,xls,xlsx"},
	        ],
	        max_file_size: '10mb', //文件最大尺寸
	         // prevent_duplicates: true //不允许选取重复文件
	       },
	        init: {
	          PostInit: function() {
				  
			  },
	          FilesAdded: function(up, files) {
	            plupload.each(files, function(file) {
					if(_this.word_list.length < 5) {
						_this.word_list.push({
							id:file.id,
							filename:file.name,
							size:file.size,
							pro:0
						})
						_this.emit('word')
						// console.log('up');
						_this.set_upload_param(uploader, file.name, false,file.id,_this.word_list);
					}
	            });
	          },
			  
	          BeforeUpload: function(up, file) {
				  // console.log('beforeup');
				// _this.set_upload_param(up, file.name, true);
	          },
	
	          UploadProgress: function(up, file) { 
	            _this.word_list.forEach((item) => {
					if(item.id == file.id) {
						item.pro = file.percent;
					}
				})
	          },
	
	          FileUploaded: function(up, file, info) {
				  // console.log(info);
	            if (info.status == 200) {
					// console.log(info);
					var array = info.responseHeaders.split("\r\n");
					var infoObj = {}
					array.forEach((item) => {
						  var arr = item.split(':');
						  if(arr.length > 1) {
							  infoObj[arr[0]] = arr[1].replace(/"/g,"").replace(/ /g, '');
						  }
					})
					_this.word_list.forEach((item) => {
						if (item.id == file.id) {
							item.etag = infoObj.etag;
						}
					})
					_this.emit('word')
					// console.log(_this.word_list);
	            } else if (info.status == 203) {
					console.log("上传到OSS成功，但是oss访问用户设置的上传回调服务器失败，失败原因是:" + info.response)
	            } else {
	              // console.log(info.response)
	            }
	          },
	
	          Error: function(up, err) {
	            if (err.code == -600) {
					console.log("选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小");	
	            } else if (err.code == -601) {
					console.log("选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型");	
	            } else if (err.code == -602) {
					console.log("这个文件已经上传过一遍了");
	            } else {
					console.log("Error xml:" + err.response) 
	            }
	          }
	        }
	      });
	     uploader.init();
	    },
		initPlUploaderImg() {
			const _this = this;
		    var uploader = new plupload.Uploader({
		    runtimes: "html5,flash,silverlight,html4",
		    browse_button: this.btnId,
			multi_selection: false,
			// flash_swf_url:'/static/plupload/js/Moxie.swf',
			// silverlight_xap_url:'/static/plupload/js/Moxie.xap',
		    //multi_selection: false,
		    // container: document.getElementById('container'),
		    // flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
		    // silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
		    url: baseUrl.OccAli,
		    filters: {
		       mime_types: [
					  {title : "img files", extensions : "png,jpg,HEIC,HEIF,heic,heif,jpeg,JPEG"},
			 ],
		      max_file_size: "100mb" //最大只能上传10mb的文件
		      // prevent_duplicates: true //不允许选取重复文件
		    },
			
		    init: {
		      PostInit: function() {
		        // document.getElementById("ossfile").innerHTML = "";
		        // document.getElementById("postfiles").onclick = function() {
		        //   set_upload_param(uploader, "", false);
		        //   return false;
		        // };
				
		      },
		      FilesAdded: function(up, files) {
		        plupload.each(files, function(file) {
					if(_this.img_list.length < 5) {
						var obj = {
							id:file.id,
							filename:file.name,
							size:file.size,
							pro:0
						}
						 previewImage(file, function(url) {
							obj.src = url
						});
						_this.img_list.push(obj);
						_this.emit('img')
						_this.set_upload_param(uploader, file.name, false,file.id,_this.img_list);
					}
		        });
				//console.log(_this.word_list);
		      },
			
		      BeforeUpload: function(up, file) {
				_this.set_upload_param(up, file.name, true);
		      },
			
		      UploadProgress: function(up, file) {
		        _this.img_list.forEach((item) => {
					if(item.id == file.id) {
						item.pro = file.percent;
					}
				})
		      },
			
		      FileUploaded: function(up, file, info) {
				  // console.log(info);
		        if (info.status == 200) {
					// console.log(info);
					var array = info.responseHeaders.split("\r\n");
					var infoObj = {}
					array.forEach((item) => {
						  var arr = item.split(':');
						  if(arr.length > 1) {
							  infoObj[arr[0]] = arr[1].replace(/"/g,"").replace(/ /g, '');
						  }
					})
					//console.log(infoObj);
					//console.log(_this.img_list);
					_this.img_list.forEach((item) => {
						if (item.id == file.id) {
							item.etag = infoObj.etag;
						}
					})
					// console.log(_this.img_list);
					_this.emit('img')
		        } else if (info.status == 203) {
					console.log("上传到OSS成功，但是oss访问用户设置的上传回调服务器失败，失败原因是:" + info.response)
		        } else {
		          // console.log(info.response)
		        }
		      },
			
		      Error: function(up, err) {
		        if (err.code == -600) {
					console.log("选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小");	
		        } else if (err.code == -601) {
					console.log("选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型");	
		        } else if (err.code == -602) {
					console.log("这个文件已经上传过一遍了");
		        } else {
					console.log("Error xml:" + err.response) 
		        }
		      }
		    }
		  });
		 uploader.init();
		}
	  }
	};
</script>
<style lang="scss">
	.choiceBtn {
		color:#0096ff;
	}
	.list_item {
		flex: none;
		background-color: #f24545;
		color: #fff;
		border-radius: 4px;
		font-size: 14px;
		padding: 5px 8px;
		margin-right: 15px;
		opacity: 0.5;
		margin-top: 10px;
		width: 600rpx;
		display: flex;
		justify-content: space-between;
		.iconfont {
			font-size: 18rpx;
		}
	}
</style>